package com.xzy.source;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.event.EventListener;

import java.util.Date;

/**
 * @author xzy.xiao
 * @date 2023/3/15  10:30
 */
@Slf4j
public class Main {

    public static void main(String[] args) {

        // 通过接口和注解定义监听器
        test1();

        // 通过 registerBean 和 addApplicationListener 方法添加监听器
//        test2();

        // 调用 refresh 前后添加监听器
//        test3();
    }

    /**
     * 调用 refresh 前后添加监听器
     */
    private static void test3() {
        // 创建容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        // 注册事件监听器
        applicationContext.addApplicationListener(new RowEventListener());
        applicationContext.refresh();
        applicationContext.addApplicationListener(new RowEventListener());

        for (int i = 0; i < 3; i++) {
            applicationContext.publishEvent(new RowEvent(Main.class, new Date()));
        }
    }

    /**
     * 通过 registerBean 和 addApplicationListener 方法添加监听器
     */
    private static void test2() {
        // 创建容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        // 注册事件监听器
        applicationContext.registerBean("rowEventListener", RowEventListener.class);
        applicationContext.addApplicationListener(new RowEventListener());
        applicationContext.refresh();

        for (int i = 0; i < 3; i++) {
            applicationContext.publishEvent(new RowEvent(Main.class, new Date()));
        }
    }

    /**
     * 通过接口和注解定义监听器
     */
    private static void test1() {
        // 创建容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        // 注册事件监听器
        applicationContext.registerBean("genericEventListener", GenericEventListener.class); // 通过接口定义的监听器
        applicationContext.registerBean("main", Main.class); // 通过注解定义的监听器
        applicationContext.refresh();

        for (int i = 0; i < 3; i++) {
            applicationContext.publishEvent(new RowEvent(Main.class, new Date()));
            applicationContext.publishEvent(new GenericEvent<>(Main.class, new Date()));
        }
    }

    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @EventListener
    public void onApplicationEvent(RowEvent event) {
        log.info("onApplicationEvent 监听到事件 => {}", event);
    }
}
